import { Request, Response } from "express";
import { AppDataSource } from "../config/db"; // 数据库连接
import { TodoModel } from "../models/Todo.model"; // 待办实体
import { success, fail } from "../utils/response"; // 统一响应工具
import _ from "lodash";

const todoRepo = AppDataSource.getRepository(TodoModel); // 待办仓库
/**
 * 获取指定id的待办
 * @param req
 * @param res
 */
export const getTodo = async (req: Request, res: Response) => {
  const { id } = req.params;
  const todo = await todoRepo.findOne({ where: { id: parseInt(id) } });
  if (!todo) {
    return fail(res, 404, "待办不存在");
  }
  success(res, todo);
};

/**
 * @desc    获取当前用户的所有待办
 * @route   GET /api/todos
 * @access  Private
 */
export const getTodos = async (req: Request, res: Response) => {
  try {
    const todos = await todoRepo.find({
      where: { userId: req.user!.userId }, // 只查当前用户的待办
      order: { id: "DESC" }, // 按 ID 倒序
    });
    success(res, todos);
  } catch (err) {
    fail(res, 500, "获取待办失败", err);
  }
};

/**
 * @desc    添加新的待办
 * @route   POST /api/todos
 * @access  Private
 */
export const addTodo = async (req: Request, res: Response) => {
  const { text } = req.body;

  // 参数验证
  if (!text || text.trim() === "") {
    return fail(res, 400, "待办内容不能为空");
  }

  try {
    const newTodo = todoRepo.create({
      text: text.trim(),
      done: false,
      userId: req.user!.userId,
    });
    await todoRepo.save(newTodo);
    success(res, newTodo, "添加成功");
  } catch (err) {
    fail(res, 500, "添加待办失败", err);
  }
};

/**
 * @desc    删除指定待办
 * @route   DELETE /api/todos/:id
 * @access  Private
 */
export const deleteTodo = async (req: Request, res: Response) => {
  const { id } = req.params;

  try {
    const todo = await todoRepo.findOne({
      where: { id: parseInt(id), userId: req.user!.userId },
    });

    if (!todo) {
      return fail(res, 404, "待办不存在或无权操作");
    }

    await todoRepo.remove(todo);
    success(res, null, "删除成功");
  } catch (err) {
    fail(res, 500, "删除待办失败", err);
  }
};

/**
 * @desc    切换待办完成状态, 更新代办信息
 * @route   PATCH /api/todos/:id
 * @access  Private
 */
export const toggleDone = async (req: Request, res: Response) => {
  const { id } = req.params;
  const { text, done } = req.body;

  if (_.isNil(done) && _.isEmpty(text)) {
    return fail(res, 400, "请提供待办状态或者待办内容");
  }

  try {
    let todo = await todoRepo.findOne({
      where: { id: parseInt(id), userId: req.user!.userId },
    });

    if (!todo) {
      return fail(res, 404, "待办不存在或无权操作");
    }
    todo = { ...todo, done, text };
    await todoRepo.save(todo);
    success(res, todo, "更新成功");
  } catch (err) {
    console.log(err);
    fail(res, 500, "更新待办失败", err);
  }
};
